package com.amado.easyui2.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.amado.easyui2.constant.GlobalConstants;

public class EncodingFilter implements Filter {
	// 初始化配置参数
	private static final String MESSAGES = "UTF-8";
	//拦截器不拦截images hetml css login.jsp
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) arg0;
		HttpServletResponse httpResponse = (HttpServletResponse) arg1;
		httpRequest.setCharacterEncoding(MESSAGES);
		httpResponse.setHeader("content-type", "application/json; charset=utf-8");
		String path = httpRequest.getServletPath();//获取路径
		if ("/login.jsp".equals(path) || "/userLoginServlet.do".equals(path)) {
			//调用下一个过滤器，如果没有过滤器就调用到SERVLET
			arg2.doFilter(arg0, arg1);
		} else {
			//做回话校验，判断SESSION中有没有MESSAGE，没有认为没有登录重定向到登录页面
			HttpSession session = httpRequest.getSession();
			String messAge = (String) session.getAttribute(GlobalConstants.SESSION_USER);
			if (messAge == null) {
				httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
			} else {
				arg2.doFilter(arg0, arg1);
			}
		}
	}

}
